#!/usr/bin/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# Send MQTT discovery information to Home Assistant and service information
# to the Supervisor (for other add-ons).
# ==============================================================================
readonly SYSTEM_USER="/data/system_user.json"
declare config
declare discovery_password
declare service_password

# Wait for mosquitto to start before continuing
bashio::net.wait_for 1883

# Read the existing values
discovery_password=$(bashio::jq "${SYSTEM_USER}" ".homeassistant.password")
service_password=$(bashio::jq "${SYSTEM_USER}" ".addons.password")

# Create discovery config payload for Home Assistant
config=$(bashio::var.json \
    host "$(hostname)" \
    port "^1883" \
    ssl "^false" \
    protocol "3.1.1" \
    username "homeassistant" \
    password "${discovery_password}" \
)

# Send discovery info
if bashio::discovery "mqtt" "${config}" > /dev/null; then
    bashio::log.info "Successfully send discovery information to Home Assistant."
else
    bashio::log.error "Discovery message to Home Assistant failed!"
fi

# Create service config payload for other add-ons
config=$(bashio::var.json \
    host "$(hostname)" \
    port "^1883" \
    ssl "^false" \
    protocol "3.1.1" \
    username "addons" \
    password "${service_password}" \
)

# Send service info
if bashio::services.publish "mqtt" "${config}" > /dev/null 2>&1; then
    bashio::log.info "Successfully send service information to the Supervisor."
else
    bashio::log.error "Service message to Supervisor failed!"
fi
